﻿namespace AddressBook.Mvc.Controllers
{
	#region "Using Statements"

	using System;
	using System.Collections.Generic;
	using System.Linq;
	using System.Web;
	using System.Web.Mvc;

	using AddressBook.Business.Person;

	using MvcContrib.Pagination;
	using System.Collections;

	#endregion

	public class HomeController : Controller
	{
		//
		// GET: /Home/

		public ActionResult Index(string searchCriteria, int? page)
		{
			ContactModel contactModel = new ContactModel();
			ContactList contacts;
			int pageNo = page ?? 1;

			if (String.IsNullOrEmpty(searchCriteria))
			{
				ViewData["SearchCriteria"] = String.Empty;
				contacts = ContactList.GetContactList();
			}
			else
			{
				ViewData["SearchCriteria"] = searchCriteria;
				contacts = ContactList.GetContactList(searchCriteria);
			}

			IPagination<ContactInfo> pagedContacts = PaginationHelper.AsPagination<ContactInfo>(contacts, pageNo, 10);
			contactModel.Pagination = pagedContacts;
			contactModel.Contacts = contacts.Skip(pagedContacts.PageSize * (pagedContacts.PageNumber - 1)).Take(pagedContacts.PageSize);
			return View(contactModel);
		}

		public ActionResult Edit(Int32 id)
		{
			Contact contact = Contact.GetContact(id);

			return View(contact);
		}

		[HttpPost]
		public ActionResult Edit(Int32 id, FormCollection collection)
		{
			Contact contact = Contact.GetContact(id);

			try
			{
				UpdateModel(contact);

				contact = contact.Save();
				return RedirectToAction("Index");
			}
			catch
			{
				return View(contact);
			}
		}

		[AcceptVerbs(HttpVerbs.Delete)]
		public ActionResult Delete(Int32 id)
		{
			Contact.DeleteContact(id);
			ContactList contacts = ContactList.GetContactList();

			return RedirectToAction("Index");
		}

		public ActionResult Create()
		{
			Contact contact = Contact.NewContact();
			return View(contact);
		}

		[HttpPost]
		public ActionResult Create(FormCollection collection)
		{
			Contact contact = Contact.NewContact();

			try
			{
				UpdateModel(contact);

				contact = contact.Save();
				return RedirectToAction("Index");
			}
			catch
			{
				return View(contact);
			}
		}

		public class ContactModel
		{
			public IPagination<ContactInfo> Pagination { get; set; }
			public IEnumerable<ContactInfo> Contacts { get; set; }
		}
	}
}

